import {
  actionData
} from './config.js'

let main, receiver, filter, intentInstance
let scanFlag = false // 是否开启了激光扫描，默认关闭

// 获取设备品牌名，并转为小写，防止大小写区分从而找不到广播
const deviceBrand = uni.getSystemInfoSync().deviceBrand?.toLocaleLowerCase();

function setDeviceActionData() {
  const findAction = actionData.find(item => item.deviceBrand == deviceBrand)
  if (findAction && Object.keys(findAction).length) {
    uni.setStorageSync('device-action-data', findAction)
  } else {
    console.error('未查询到该PDA设备的广播数据')
  }
}
setDeviceActionData()


/**
 * 初始化激光扫描
 * @param {String} broadcastAction 广播动作 例：android.intent.ACTION_DECODE_DATA
 * @param {String} broadcastTag 广播标签 例：barcode_string
 */
export function initScan() {
  // 初始化广播动作
  const broadcastAction = uni.getStorageSync('device-action-data').action
  const broadcastTag = uni.getStorageSync('device-action-data').tag

  // 若main不为空则表明已进行过初始化
  if (main) return
  // 条件编译 HTML5+ 扩展规范，否则运行到h5、小程序等平台会出现 plus is not defined 错误
  // #ifdef APP
  // 获取Android主Activity
  main = plus.android.runtimeMainActivity()
  // 获取Android意图过滤类
  let IntentFilter = plus.android.importClass('android.content.IntentFilter')
  // 实例化意图过滤
  filter = new IntentFilter()
  // 获取意图广播，addAction内改为广播动作
  filter.addAction(broadcastAction)
  receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
    onReceive: function(context, intent) {
      plus.android.importClass(intent)
      // getStringExtra内改为广播标签
      let code = intent.getStringExtra(broadcastTag)
      console.log('广播监听扫描信息 ==== code :', code)
      uni.$emit('e-laser-scan', code)
    }
  })
  // #endif
}

/**
 * 开启扫描
 */
export function startScan() {
  // #ifdef APP
  if (main && !scanFlag) {
    main.registerReceiver(receiver, filter)
    console.log('==== 开启扫描 ====')
    scanFlag = true
  }
  // #endif
}

/**
 * 关闭扫描
 */
export function stopScan() {
  // #ifdef APP
  if (main && scanFlag) {
    main.unregisterReceiver(receiver)
    console.log('==== 关闭扫描 ====')
    // 重置参数
    main = null
    receiver = null
    filter = null
    intentInstance = null
    scanFlag = false
  }
  // #endif
}


/**
 * 手动调用扫描 (非PDA物理按键)
 * @param {Object} keyAction 按键广播动作
 */
export function triggerScan() {
  // 初始化广播动作
  const triggerAction = uni.getStorageSync('device-action-data')?.triggerAction
  if (!triggerAction) {
    uni.showToast({
      title: '请使用设备物理激光扫描按键',
      icon: 'none',
    })
    return
  }
  // #ifdef APP
  // 获取Android意图类
  let Intent = plus.android.importClass('android.content.Intent')
  // 实例化意图
  intentInstance = new Intent()
  // 定义意图，模拟按下激光的物理按键映射，由厂商提供
  intentInstance.setAction(triggerAction)
  // 广播这个意图
  main.sendBroadcast(intentInstance)
  // #endif
}